"use client";
import React, { memo, useEffect } from "react";
import type { FC, ReactNode } from "react";
import { useUser, useClerk } from "@clerk/nextjs";
import { userService } from "@/services/api";
import { useAuthhook } from "@/hooks/useAuth"; // 引入自定义 hook
// import { useDispatch } from "react-redux";
// import { setLogin, setLogout } from "@/store/reducers/authReducer";

//使用自定义hook+sessionStorage管理登录状态，替换redux reducer

interface IProps {
  children?: ReactNode;
}

const getGreeting = () => {
  const hour = new Date().getHours();
  if (hour < 5) return "夜深了";
  if (hour < 12) return "早上好";
  if (hour < 18) return "下午好";
  return "晚上好";
};
const TopBar: FC<IProps> = () => {
  const [greeting, setGreeting] = React.useState(getGreeting());
  const { user = { primaryEmailAddress: { emailAddress: "用户" } } } =
    useUser();
  // const dispatch = useDispatch();
  const { login, logout } = useAuthhook(); // 替代 dispatch(setLogin(...))
  const { signOut } = useClerk();
  useEffect(() => {
    const timer = setInterval(() => {
      setGreeting(getGreeting());
    }, 60000);
    return () => clearInterval(timer);
  }, []);
  // 登录处理，挂载时
  useEffect(() => {
    if (
      user?.primaryEmailAddress?.emailAddress &&
      user?.primaryEmailAddress?.emailAddress !== "用户"
    )
      userService
        .registerOrFind(user?.primaryEmailAddress?.emailAddress)
        .then((res) => {
          console.log(res);
          // dispatch(setLogin({ userId: res.user.id, email: res.user.email }));
          const userInfo = {
            userId: res.user.id,
            email: res.user.email,
          };
          login(userInfo);
        });
  }, [user?.primaryEmailAddress?.emailAddress]);

  //退出登录处理
  const handleSignout = () => {
    logout();
    signOut({ redirectUrl: "/" });
  };

  return (
    <div className="mybar">
      <div className="greet">
        {greeting + " , " + user?.primaryEmailAddress?.emailAddress || "用户"}
      </div>
      <div className="out" onClick={() => handleSignout()}>
        退出登录
      </div>
      <style jsx>
        {`
          .mybar {
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 20px;
            color: white;
          }
          .out:hover {
            color: #000;
            cursor: pointer;
          }
        `}
      </style>
    </div>
  );
};
export default memo(TopBar);
